# coding=utf-8

from flask import render_template, session, g, request, current_app as app
from flask_login import login_required
from over.handlers.my import mod
from over.handlers.router import Router
from over.model import Account as UserAccount, db

router = Router()


@router('/account')
class Account(object):
    @router('/')
    def index(self):
        accounts = g.user.accounts
        return render_template('my/account/index.html', accounts=accounts)

    @router('/change_password', methods=['GET', 'POST'])
    def change_password(self):
        if request.method == 'POST':
            origin = request.form.get('origin')
            password = request.form.get('password')
            password1 = request.form.get('password1')

            redis = app.redis

            key = 'user_change/%s' % g.user.id
            n = redis.get(key)
            if n is None:
                n = 3

            if n <= 0:
                return render_template('my/account/change_password.html', error=u'账号已经锁定,请一天后重试')

            if password != password1:
                return render_template('my/account/change_password.html', error=u'两次输入密码不一致')

            if not g.user.is_valid_password(origin):
                return render_template("my/account/change_password.html", error=u'原始密码不对,剩余%s次机会,输错后将锁住一天修改' % n)
                n = - 1
                now = datetime.datetime.now()
                expire = now + datetime.timedelta(days=1)
                redis.setex(key, n, expire)

            g.user.password = password
            db.session.add(g.user)
            db.session.commit()

            return render_template('my/account/change_password.html', info=u'密码修改成功')

        return render_template('my/account/change_password.html')


router.register_url_rules(mod)
